package com.hmall.service;

import com.hdmall.business.common.common.ServerResponse;
import com.hdmall.business.common.common.ResponseCode;
import com.hdmall.business.common.common.ServerResponse;
import com.hdmall.business.common.util.DecimalFormatUtrils;
import com.hmall.mapper.DictionMapper;
import com.hmall.mapper.MallOrderMapper;
import com.hmall.mapper.MallPaymentVoucherMapper;
import com.hmall.model.Diction;
import com.hmall.model.MallOrder;
import com.hmall.model.MallPaymentVoucher;
import com.hmall.vo.AccountPeriodPayVo;
import com.hmall.vo.MallPaymentUnpayVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 支付操作
 */
@Service
public class PaymentService {
    @Autowired
    private MallOrderMapper orderMapper;
    @Autowired
    private MallPaymentVoucherMapper paymentVoucherMapper;
    @Autowired
    private DictionMapper dictionMapper;

    //线下分期支付
    public ServerResponse underLineAccountPeriodPay(Integer userId,AccountPeriodPayVo accountPeriodPayVo){

        accountPeriodPayVo.setIsDeposit(0);

        try {
            paymentVoucherMapper.insertPaymentVoucher(accountPeriodPayVo,userId);
            paymentVoucherMapper.adoptVoucherByOrderNo(accountPeriodPayVo.getOrderNo());

        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByStatus(ResponseCode.PAYMENTVOUCHER_INSERT_ERROR.getCode(),ResponseCode.PAYMENTVOUCHER_INSERT_ERROR.getDesc(),null);
        }
        MallPaymentUnpayVo paymentUnpayVo= paymentVoucherMapper.selectUnpaymentVo(accountPeriodPayVo.getOrderNo());

        if(paymentUnpayVo==null){
            paymentVoucherMapper.insertUnpaymentVo(accountPeriodPayVo.getOrderNo(),accountPeriodPayVo.getUnpayPeyment(),0);
        }
        if(accountPeriodPayVo.getUnpayPeyment()<=0.0){
            paymentVoucherMapper.updateUnpaymentIsPay(accountPeriodPayVo.getOrderNo());
            paymentVoucherMapper.updateUnpaymentVo(accountPeriodPayVo.getOrderNo(),accountPeriodPayVo.getUnpayPeyment());
            return ServerResponse.createBySuccess("已经交易完成");
        }else {
            paymentVoucherMapper.updateUnpaymentVo(accountPeriodPayVo.getOrderNo(),accountPeriodPayVo.getUnpayPeyment());
        }

        return ServerResponse.createBySuccess(accountPeriodPayVo);
    }

    //线下定金支付
    public ServerResponse<AccountPeriodPayVo> underLineDepositPay(Integer userId,Long orderNo,Double deposit,String voucherImg,Integer paymentType){

        //确认是定金支付状态
            AccountPeriodPayVo accountPeriodPay=new AccountPeriodPayVo();
            accountPeriodPay.setFactPayment(deposit);
            accountPeriodPay.setIsDeposit(1);
            accountPeriodPay.setInterestRate(0.0);
            accountPeriodPay.setInterest(0.0);
            accountPeriodPay.setVoucherImg(voucherImg);
            accountPeriodPay.setOrderNo(orderNo);
            MallOrder order=orderMapper.selectByOrderNo(orderNo);
            Double unpayment=DecimalFormatUtrils.dataFomateTwo(order.getPayment().doubleValue()-deposit);
            accountPeriodPay.setUnpayPeyment(unpayment);
            List<MallPaymentVoucher> paymentVoucherList;
            try {
                paymentVoucherList=paymentVoucherMapper.selectVoucherByOderNo(orderNo);
            } catch (Exception e) {
                e.printStackTrace();
                return ServerResponse.createByStatus(ResponseCode.PAYMENTVOUCHER_INSERT_ERROR.getCode(),ResponseCode.PAYMENTVOUCHER_INSERT_ERROR.getDesc(),null);
            }
            if(paymentVoucherList.size()>0){
                return ServerResponse.createByStatus(ResponseCode.PAYMENTVOUCHER_DEPOSIT_REPEAT.getCode(),ResponseCode.PAYMENTVOUCHER_DEPOSIT_REPEAT.getDesc(),null);
            }
            try {
                paymentVoucherMapper.insertPaymentVoucher(accountPeriodPay,userId);
                orderMapper.updatePaymentTypeOrder(orderNo,paymentType);
                paymentVoucherMapper.adoptVoucherByOrderNo(orderNo);
                paymentVoucherMapper.insertUnpaymentVo(orderNo,unpayment,0);
            } catch (Exception e) {
                e.printStackTrace();
                return ServerResponse.createByStatus(ResponseCode.PAYMENTVOUCHER_INSERT_ERROR.getCode(),ResponseCode.PAYMENTVOUCHER_INSERT_ERROR.getDesc(),null);
            }


            return ServerResponse.createBySuccess(accountPeriodPay);
    }

    //根据分期和利率计算
    /**
     *
     * @param orderNo
     * @param accountPeriod 分期
     * @param depositRate 月利率
     * @return
     */
    public ServerResponse<Map<String,Object>> operAccountPeriod(Long orderNo,Integer accountPeriod,Double depositRate){
        MallOrder order=null;
        try {
            order= orderMapper.selectByOrderNo(orderNo);
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByStatus(ResponseCode.ORDER_SELECT_ERROR.getCode(),ResponseCode.ORDER_SELECT_ERROR.getDesc(),null);
        }
        if(order==null){
            return ServerResponse.createByStatus(ResponseCode.ORDER_SELECT_NULL.getCode(),ResponseCode.ORDER_SELECT_NULL.getDesc(),null);
        }
        Double payment=order.getPayment().doubleValue();
        //查询定金
        Double deposit= null;
        try {
            deposit = paymentVoucherMapper.selectDeposit(orderNo);
        } catch (Exception e) {
            e.printStackTrace();
            deposit=0.0;
        }
        if(deposit==null){
            deposit=0.0;
        }
        Double sumPayment= null;
        try {
            sumPayment = paymentVoucherMapper.sumPayment(orderNo);
        } catch (Exception e) {
            e.printStackTrace();
            sumPayment=0.0;
        }
        if(sumPayment==null){
            sumPayment=0.0;
        }
        //每月本息
        Double interest=DecimalFormatUtrils.dataFomateTwo((payment-deposit-sumPayment)*depositRate);
        //每月本金
        Double currentPrincipal=DecimalFormatUtrils.dataFomateTwo((payment-deposit)/accountPeriod);
        //每月还款额
        Double factPayment=DecimalFormatUtrils.dataFomateTwo(currentPrincipal+interest);
        //剩余尾款
        Double unpayPeyment=DecimalFormatUtrils.dataFomateTwo(payment-deposit-sumPayment);
        Map<String,Object> map=new HashMap<String,Object>();
        if(unpayPeyment>0.0){
            map.put("interest",interest);
            map.put("currentPrincipal",currentPrincipal);
            map.put("factPayment",factPayment);
            map.put("unpayPeyment",unpayPeyment);
            map.put("accountPeriod",accountPeriod);
            map.put("depositRate",depositRate);
        }else{
            Map<String,Integer> stMap=selectPayPasStatus(orderNo).getData();
            Integer payPasStatus= stMap.get("payPasStatus");
            if(payPasStatus==3){
                return ServerResponse.createByStatus(ResponseCode.ORDER_ORDER_SUCCESS.getCode(),"交易已完成",null);
            }
            MallPaymentUnpayVo paymentUnpayVo= paymentVoucherMapper.selectUnpaymentVo(orderNo);
            Double unpay= paymentUnpayVo.getUnpayPayment();
            currentPrincipal=unpay;
            factPayment=unpay;
//            unpayPeyment=unpay;
            map.put("interest",0.0);
            map.put("currentPrincipal",currentPrincipal);
            map.put("factPayment",factPayment);
            map.put("unpayPeyment",0.0);
            map.put("accountPeriod",accountPeriod);
            map.put("depositRate",depositRate);
        }
        return  ServerResponse.createBySuccess(map);


    }
    //获取定金列表
    public ServerResponse<List<Map<String,Double>>> selectDeposits(Long orderNo){
        List<Map<String,Double>> list=new ArrayList<Map<String,Double>>();
        Diction dicDepositRates=dictionMapper.selectByDictionKey("deposit_rates");
        String depositRates=dicDepositRates.getValue();
        String[] depositRatesArr=null;
        if(depositRates!=null){
            depositRatesArr=depositRates.split(",");
            for (String depositRate:depositRatesArr) {
               Map<String,Double> map=operDeposit(Double.parseDouble(depositRate),orderNo).getData();
               list.add(map);
            }
        }
        return ServerResponse.createBySuccess(list);
    }
    //获取分期列表
    public ServerResponse<List<Map<String,Object>>> selectAccountPeriodsDeposits(Long orderNo){
        List<Map<String,Object>> list=new ArrayList<Map<String,Object>>();
        Diction dicInterestRates =dictionMapper.selectByDictionKey("interest_rates");
        Diction dicAccountPeriods=dictionMapper.selectByDictionKey("account_periods");
        String interestRates=dicInterestRates.getValue();
        String accountPeriods=dicAccountPeriods.getValue();
        String[] interestRateArr=null;
        String[] accountPeriodsArr=null;
        if(interestRates!=null){
            interestRateArr=interestRates.split(",");
            accountPeriodsArr=accountPeriods.split(",");
            for(int i=0;i<interestRateArr.length;i++){
                Map<String,Object> map=operAccountPeriod(orderNo,Integer.parseInt(accountPeriodsArr[i]),Double.parseDouble(interestRateArr[i])).getData();
                list.add(map);
            }
        }
        return ServerResponse.createBySuccess(list);
    }
    //查询账期和利率等字典信息
    public ServerResponse selectUnderLinePaymentDictions(){
        Diction dicInterestRates =dictionMapper.selectByDictionKey("interest_rates");
        Diction dicDepositRates=dictionMapper.selectByDictionKey("deposit_rates");
        Diction dicAccountPeriods=dictionMapper.selectByDictionKey("account_periods");
        Diction dicFullPayments=dictionMapper.selectByDictionKey("full_payment");
        String interestRates=dicInterestRates.getValue();
        String depositRates=dicDepositRates.getValue();
        String accountPeriods=dicAccountPeriods.getValue();
        String fullPayments=dicFullPayments.getValue();
        String[] interestRateArr=null;
        String[] depositRatesArr=null;
        String[] accountPeriodsArr=null;
        String[] fullPaymentsArr=null;
        Map<String,String[]> map =new HashMap<String,String[]>();
        if(interestRates!=null){
            interestRateArr=interestRates.split(",");
            map.put("interestRateArr",interestRateArr);
        }
        if(depositRates!=null){
            depositRatesArr=depositRates.split(",");
            map.put("depositRatesArr",depositRatesArr);
        }
        if(accountPeriods!=null){
            accountPeriodsArr=accountPeriods.split(",");
            map.put("accountPeriodsArr",accountPeriodsArr);
        }
        if(fullPayments!=null){
            fullPaymentsArr=fullPayments.split(",");
            map.put("fullPaymentsArr",fullPaymentsArr);
        }
        return  ServerResponse.createBySuccess(map);
    }
    //计算定金

    /**
     *
     * @param depositRate 定金比率
     * @return
     */
    public ServerResponse<Map<String,Double>> operDeposit(Double depositRate,Long orderNo){
        MallOrder order=null;
        try {
            order= orderMapper.selectByOrderNo(orderNo);
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByStatus(ResponseCode.ORDER_SELECT_ERROR.getCode(),ResponseCode.ORDER_SELECT_ERROR.getDesc(),null);
        }
        if(order!=null&&order.getPayment().doubleValue()>0.0){
            Map<String,Double> map =new HashMap<String,Double>();
            Double deposit=DecimalFormatUtrils.dataFomateTwo(order.getPayment().doubleValue()*depositRate);
            map.put("deposit",deposit);
            map.put("depositRate",depositRate);
            return ServerResponse.createBySuccess(map);

        }else{
            return ServerResponse.createBySuccess(null);
        }

    }
    //查询付款通道状态 1 定金 2 分期 3完成
    public ServerResponse<Map<String,Integer>> selectPayPasStatus(Long orderNo){
        Map<String,Integer> map=new HashMap<String,Integer>();
        Integer payPasStatus=3;
        MallOrder order=null;
        try {
            order= orderMapper.selectByOrderNo(orderNo);
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByStatus(ResponseCode.ORDER_SELECT_NULL.getCode(),ResponseCode.ORDER_SELECT_NULL.getDesc(),null);
        }
        payPasStatus=1;
        int isPay=0;
        try {
            isPay= paymentVoucherMapper.selectUnaymentIsPay(orderNo);
        } catch (Exception e) {
            e.printStackTrace();
            payPasStatus=2;
        }
        if(isPay==1){
            payPasStatus=3;
            map.put("payPasStatus",payPasStatus);
            return ServerResponse.createBySuccess(map);
        }
        List<MallPaymentVoucher> list= null;
        try {
            list = paymentVoucherMapper.selectVoucherByOderNo(orderNo);
        } catch (Exception e) {
            e.printStackTrace();
            payPasStatus=1;
        }
        if(list.size()>0){
            payPasStatus=2;
            map.put("payPasStatus",payPasStatus);
            return ServerResponse.createBySuccess(map);
        }
        payPasStatus=1;
        map.put("payPasStatus",payPasStatus);
        return ServerResponse.createBySuccess(map);

    }


}
